﻿using System;
using System.IO;
using SimpleServiceBus.Bus.MessageManagement.Serialization;

namespace SimpleServiceBus.Bus.Pipeline.PipelineComponents
{
    public class MessageBodySerializationComponent : PipelineComponentBase
    {
        public MessageBodySerializationComponent():base("Serializer")
        {
        }

        protected override void ProcessMessage(MessageEnvelope messageEnvelope, IMessageContext context)
        {
            var svc = context.GetLocalService<IMessageSerializer>();
            if (svc != null)
            {
                if (Pipeline.PipelineDirection == PipelineDirection.Receive)
                {
                    if (messageEnvelope.Payload != null)
                    {
                        try
                        {
                            using (var stream = new MemoryStream(messageEnvelope.Payload))
                            {
                                messageEnvelope.Body = svc.Deserialize(stream);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("There was a problem deserializing a message:" + ex.Message, ex);
                        }
                    }
                }
                else if (Pipeline.PipelineDirection == PipelineDirection.Send)
                {
                    if (messageEnvelope.Body != null)
                    {
                        try
                        {
                            using (var payload = new MemoryStream())
                            {
                                svc.Serialize(messageEnvelope.Body, payload);
                                var data = new byte[payload.Length];
                                Array.Copy(payload.GetBuffer(), data, data.Length);
                                messageEnvelope.Payload = data;
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("There was a problem serializing a message:" + ex.Message, ex);
                        }
                    }
                }
            }
        }
    }
}